package utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.shishi.tech.paipai.application.BaseApplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import log.LogManager;
import utils.commonbean.PhoneContactBean;

public class PhoneUtil {

    /**
     * 获取uuid
     */
    public static String getUUID() {
        return getUUID(BaseApplication.getInstance());
    }

    /**
     * 获取uuid
     */
    public static String getUUID(Context activity) {
        String uuid = SharedPreUtil.getInstance().getValue(SharedPreUtil.UUID);
        if (TextUtils.isEmpty(uuid)) {
            TelephonyManager manage = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
            String deviceId = manage.getDeviceId();
            if (deviceId == null) {
                deviceId = "";
            }
            deviceId = AESEncryptUtils.md5String(deviceId);//MD5
            SharedPreUtil.getInstance().putValue(SharedPreUtil.UUID, deviceId);
            uuid = deviceId;
        }
        return uuid;
    }

    /**
     * 打开软键盘
     */
    public static void openKeybord(Context mContext, EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeybord(Context mContext, EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 测试字符串是否是手机号
     * isPhoneNumber
     */
    public static boolean isPhoneNumber(String phonenumber) {
        Pattern p = Pattern.compile("[1]\\d{10}$");

        Matcher m = p.matcher(phonenumber);

        return m.matches();
    }

    public static boolean checkStringChese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static int getCharCount(String name) {
        int count = 0;
        if (name == null) {
            return count;
        }
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                count++;
            } else {
                count += 2;
            }
        }
        return count;
    }

    /**
     * 身份证校验
     * isPhoneNumber
     */
    public static boolean isIdentity(String phonenumber) {
        Pattern p = Pattern.compile("^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$");
        Matcher m = p.matcher(phonenumber);
        if (m.matches()) {
            IdcardValidator idcardValidator = new IdcardValidator();
            return idcardValidator.isValidatedAllIdcard(phonenumber);
        } else {
            return m.matches();
        }
    }

    /**
     * 测试字符串是否是密码
     * isPassWord
     * 6-20位字符串 仅支持字母和数字 区别大小写
     */
    public static boolean isPassWord(String pwd) {
        Pattern p = Pattern.compile("[a-zA-Z0-9]{6,20}");

        Matcher m = p.matcher(pwd);

        return m.matches();
    }

    /**
     * isVerificationCode 测试字符串是否符合验证码格式
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static boolean isVerificationCode(String code) {
        Pattern p = Pattern.compile("[0-9]{4,6}");

        Matcher m = p.matcher(code);

        return m.matches();
    }

    /**
     * isVerificationCode 测试字符是否为数字
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static boolean isNumber(String code) {
        Pattern p = Pattern.compile("^[0-9]*");

        Matcher m = p.matcher(code);

        return m.matches();
    }

    /**
     * getAddressContacts 获取手机通讯录联系人 (优化查询速度)
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static List<PhoneContactBean> getLoadAddresSbook(Context context) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        String contactIds = "";
        int i = 0;
        if (cursor != null) {
            // 循环遍历
            while (cursor.moveToNext()) {
                // 获得联系人的ID号
                String contactId = cursor.getString(cursor.getColumnIndex("_id"));
                map.put(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("display_name")));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    if (i != 0) {
                        contactIds += ",";
                    }
                    contactIds += contactId;
                    i++;
                }
            }
            cursor.close();
        }
        Cursor phonesCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " in ( " + contactIds + ")", null, null);
        i = 0;
        List<PhoneContactBean> loacList = new ArrayList<PhoneContactBean>();
        List<String> tempList = new ArrayList<String>();
        PhoneContactBean contacts = null;
        int nowContact = 0;
        if (phonesCursor != null) {
            if (phonesCursor.moveToFirst()) {
                do {
                    String phoneNumber = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    if (phoneNumber != null) {
                        phoneNumber = phoneNumber.replaceAll(" ", "");
                    }
                    nowContact = phonesCursor.getInt(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    contacts = new PhoneContactBean();
                    contacts.setId(nowContact + "");
                    contacts.setPhone(phoneNumber);
                    contacts.setNickName(map.get(nowContact));
                    loacList.add(contacts);
                    tempList.add(phoneNumber);
                    i++;
                } while (phonesCursor.moveToNext());
            }
            phonesCursor.close();
        }

        //获取Sim卡
        ContentResolver cr = context.getContentResolver();
        final String SIM_URI_ADN = "content://icc/adn";// SIM卡
        Uri uri = Uri.parse(SIM_URI_ADN);
        cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                contacts = new PhoneContactBean();
                contacts.setNickName(cursor.getString(cursor.getColumnIndex("name")));
                contacts.setPhone(cursor.getString(cursor
                        .getColumnIndex("number")));
                if (!tempList.contains(contacts.getPhone())) {
                    loacList.add(contacts);
                }
            }
            cursor.close();
        }
        return loacList;
    }


    /**
     * sendPhoneSMS 发送系统短息
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static void sendPhoneSMS(Context context, String phonenumber, String inviteText) {
        Uri smsToUri = Uri.parse("smsto:" + phonenumber);
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", inviteText);
        context.startActivity(intent);
    }

    public static boolean isConnectNet() {
        return isConnectNet(BaseApplication.getInstance().getBaseContext());
    }

    /**
     * isConnectNet
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static boolean isConnectNet(Context context) {
        if (context == null)
            return false;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        boolean isWifiConn = networkInfo.isConnected();

        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isMobileConn;
        if (null != networkInfo) {
            isMobileConn = networkInfo.isConnected();
        } else {
            isMobileConn = false;
        }

        if (false == isWifiConn || isMobileConn) {
            StaticVariable.NETWORK_STATE = 0;
        } else {
            if (isMobileConn) {
                StaticVariable.NETWORK_STATE = 1;
            } else if (isWifiConn) {
                StaticVariable.NETWORK_STATE = 2;
            }
        }
        return isWifiConn || isMobileConn;
    }

    /**
     * 播放系统提示声音
     */
    public static void playNotifyVoice() {
        if (null != BaseApplication.getInstance()) {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(BaseApplication.getInstance(), notification);
            if (r != null) {
                r.play();
            }
        }
    }

    /**
     * 播放系统震动
     */
    public static void playNotifyShock() {
        if (null != BaseApplication.getInstance()) {
            Vibrator vib = (Vibrator) BaseApplication.getInstance().getSystemService(Service.VIBRATOR_SERVICE);
            vib.vibrate(100); //default 100mss
        }
    }

    private static int REPLY_NOTIFY_ID = 1;

    /**
     * 普通通知栏 消息
     *
     * @param roomid  房间号码
     * @param content 显示内容
     */
    public synchronized static void playNotityBar(String roomid, String content) {
       /* if (null != BaseApplication.getInstance()) {
            Context context = BaseApplication.getInstance();
            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            long curTime = FileUtil.getCurrentTimeMillis();
            Notification notification = new Notification(R.drawable.ic_launcher, content, curTime);
            Intent intent = new Intent();
            if (BaseRoomUtil.consistentExpression(roomid, BaseRoomUtil.OFFICAL_ID)) {//官方消息
                intent.setClass(context, HeadlineActivity.class);
            } else {//聊天消息
                intent.setClass(context, ChatActivity.class);
            }
            PendingIntent contentIntent = null;
            Bundle bundle;
            REPLY_NOTIFY_ID = Integer.valueOf(BaseRoomUtil.resultRoomId(roomid));
            bundle = new Bundle();
            bundle.putSerializable("ROOMID", roomid);
            intent.putExtras(bundle);
            contentIntent = PendingIntent.getActivity(context, REPLY_NOTIFY_ID, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            MsgSetEntity msgSetEntity;
            if (BaseRoomUtil.consistentExpression(roomid, BaseRoomUtil.GROUP_ID)) {//群聊消息
                GroupEntity groupEntity = DBHelper.getInstance().queryGroupEntityById(BaseRoomUtil.resultRoomId(roomid));
                msgSetEntity = IMDBHelper.getInstance().queryMsgSet(BaseRoomUtil.resultRoomId(roomid), IMDBHelper.GROUP_RELATION);
                if (null == groupEntity || (null != msgSetEntity && null != msgSetEntity.getBother() && msgSetEntity.getBother().equals("1")))
                    return;
                if (null != msgSetEntity && !TextUtils.isEmpty(msgSetEntity.getIsAtMe()) && "1".equals(msgSetEntity.getIsAtMe())) {
                    content = "[有人@你] " + content;
                }
                contentIntent = PendingIntent.getActivity(context, Integer.parseInt(groupEntity.getGroupId()), intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                notification.setLatestEventInfo(context, groupEntity.getGroupName(), content, contentIntent);//显示消息
            } else if (BaseRoomUtil.consistentExpression(roomid, BaseRoomUtil.ROOM_ID) ||
                    BaseRoomUtil.consistentExpression(roomid, BaseRoomUtil.OFFICAL_ID)) {//私聊
                ContactEntity contactEntity = DBHelper.getInstance().selectContactEntity(BaseRoomUtil.resultRoomId(roomid),
                        BaseRoomUtil.resultRoomRelation(roomid));
                msgSetEntity = IMDBHelper.getInstance().queryMsgSet(BaseRoomUtil.resultRoomId(roomid), BaseRoomUtil.resultRoomRelation(roomid));
                if (null == contactEntity || (null != msgSetEntity && null != msgSetEntity.getBother() && msgSetEntity.getBother().equals("1")))
                    return;
                notification.setLatestEventInfo(context, contactEntity.getNickName(), content, contentIntent);//显示消息
            }
            //通知设置
            notification.when = curTime;
            notification.icon = R.drawable.ic_launcher;
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            notification.tickerText = content;//显示的提示消息
            nm.notify(REPLY_NOTIFY_ID, notification);
        }*/
    }

    /**
     * 官方消息推送 通知
     *
     * @param type
     * @param entity
     * @param content
     */
    public static void playHeadlineNotityBar(String type, Object entity, String content) {
       /* if (null != BaseApplication.getInstance()) {
            Context context = BaseApplication.getInstance();
            ContactEntity contactEntity = null;
            GroupEntity groupEntity = null;
            //获取NotifyManager对象
            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            long curTime = FileUtil.getCurrentTimeMillis();
            //设置Notify 属性
            Notification notification = new Notification(R.drawable.ic_launcher, content, curTime);
            //Intent
            Intent intent = new Intent(context, HeadlineActivity.class);
            //        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

            //PendingIntent
            PendingIntent contentIntent = null;
            Bundle bundle;
            if (type.equals("ContactEntity") && entity != null) {//个人 或微商
                contactEntity = (ContactEntity) entity;
                REPLY_NOTIFY_ID = Integer.valueOf(contactEntity.getFriendId() + "");
                bundle = new Bundle();
                bundle.putSerializable("ContactEntity", contactEntity);
                intent.putExtras(bundle);
                contentIntent = PendingIntent.getActivity(context, Integer.parseInt(contactEntity.getFriendId()), intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                notification.setLatestEventInfo(context, contactEntity.getNickName(), content, contentIntent);//显示消息
            }

            notification.when = curTime;//通知设置
            notification.icon = R.drawable.ic_launcher;
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            notification.tickerText = content;//显示的提示消息
            nm.notify(REPLY_NOTIFY_ID, notification);
        }*/
    }

    /**
     * 清除通知栏
     *
     * @param ctx
     * @param notifyId notify id
     */
    public static void cancelNotification(Context ctx, int notifyId) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) ctx
                .getSystemService(ns);
        nMgr.cancel(notifyId);
    }

    /**
     * 清除通知栏
     */
    public static void cancelNotification() {
        cancelNotification(BaseApplication.getInstance(), REPLY_NOTIFY_ID);
    }

    /**
     * 清除通知栏
     *
     * @param ctx
     */
    public static void cancelNotification(Context ctx) {
        cancelNotification(ctx, REPLY_NOTIFY_ID);
    }

    /**
     * 复制
     *
     * @param context
     * @param content
     */
    public static void copyClipboard(Context context, String content) {
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    /**
     * 转发
     *
     * @param context
     * @param content
     */
    public static void forwardClipboard(Context context, String content) {
        SharedPreUtil.getInstance().putValue(SharedPreUtil.ClIP_Data, content);
    }

    /**
     * 粘贴
     *
     * @param context
     * @return
     */
    public static String pasteClipboard(Context context) {
        return SharedPreUtil.getInstance().getValue(SharedPreUtil.ClIP_Data);
    }

    /**
     * 检测 App是否在后台运行
     *
     * @return
     */
    public static boolean isAppRunBackground() {
        Context context = BaseApplication.getInstance().getBaseContext();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    LogManager.getLogger().i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    LogManager.getLogger().i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    /**
     * 主动判断屏幕是否亮着
     *
     * @return
     */
    public static boolean isScreenOn() {
        if (null != BaseApplication.getInstance()) {
            PowerManager powerManager = (PowerManager) BaseApplication.getInstance().getSystemService(Context.POWER_SERVICE);
            if (powerManager.isScreenOn()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取状态栏高度
     * @return
     */
    public static int getStateBarHeignt(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }
}
